<?php
declare(strict_types=1);
// 商品类别
namespace app\admin_v1\controller;

use think\facade\Db; //门面模式
use app\admin_v1\model\GoodsCls as mysql; //导入模型

class GoodsCls
{

    public function _Son()
    {
        // 读数据库
        $sqldb = mysql::where([['id', '>', -1]])->order("i", "desc")->select()->toArray(); //以数组方式返回
        // 1.生成树数据
        // 2.找父ID（分解成一维数组-倒序）
        $clsTree = $this->get_Tree($sqldb, 0); //生成树数据
        // $s = array_values($cateTree); //关联数组转索引数组
        $apidb = [
            'msg' => '分类',
            'code' => 2005, //状态码
            // 'clsTree' => $clsTree,
        ];
        return json($apidb);
    }
    // 
    /** 多维转为一维数组 */
    function get_all_array_walk($array, $overturn = true)
    {
        $arr = [];
        array_walk_recursive($array, function ($value) use (&$arr) {
            array_push($arr, $value);
        });
        // 是否翻转
        if ($overturn) {
            $arr = array_reverse($arr, false); //翻转顺序的数组
        }
        // return json_encode($arr);
        return $arr;
    }

    // 
    /** 通过子类获取所有的父类 */
    function get_pids($db, $id)
    {
        $data = [];
        foreach ($db as $item) {
            if ($item['id'] == $id) {
                $arr[] = $item['id'];
                // $arr['name'] = $item['name'];
                if ($item['pid'] != 0) {
                    $arr[] = $this->get_pids($db, $item['pid']);
                    // $arr = array_merge($arr, $this->get_pids($db, $item['pid']));
                }
                $data[] = $arr;
            }
        }
        return $data;
    }
    //
    /** 递归获取所有的子分类的ID */
    function get_ids($array, $id)
    {
        $arr = [];
        foreach ($array as $v) {
            if ($v['pid'] == $id) {
                $arr[] = $v['id'];
                $arr = array_merge($arr, $this->get_ids($array, $v['id']));
            }
            ;
        }
        ;
        return $arr;
    }

    // 
    /** 递归获取所有的子分类----生成无限级分类树数据 */
    function get_Tree($db, $pid, $level = 0)
    {
        $time_int = time();
        $time = date('Y-m-d H:i:s', $time_int);
        $default = json_encode([[], $time]);
        $tree = []; //每次都声明一个新数组用来放子元素
        foreach ($db as $v) {
            if ($v['pid'] == $pid) { //匹配子记录
                // unset($v['ids']);
                $v['level'] = $level; //当前层级
                $pids = $this->get_pids($db, $v['id']); // 用自己的ID找所有祖先ID
                $v['pids'] = $this->get_all_array_walk($pids); //多维转为一维数组
                $v['pids_count'] = count($v['pids']);
                $ids = $this->get_ids($db, $v['id']); //用自己的ID找所有子孙ID
                $v['ids'] = $this->get_all_array_walk($ids, false); //多维转为一维数组
                array_unshift($v['ids'], $v['id']); //自己ID插入到数组的开头
                $v['ids_count'] = count($v['ids']);
                // $v['title'] = $v['id'] . ' - ' . $v['name'] . '(' . $level . '-' . ($v['ids_count'] - 1) . '-' . $v['end_node'] . ')';
                $v['title'] = $v['id'] . ' ' . $v['name']. '(' .Db::table('admin__i_goods')->where('cls_id',$v['id'])->count(). ')';
                //更新数据库
                $sqldb = mysql::where([['id', '=', $v['id']]])->find();
                $sqldb->pids = isset($v['pids']) ? json_encode([$v['pids'], $time]) : $default;
                $sqldb->ids = isset($v['ids']) ? json_encode([$v['ids'], $time]) : $default;
                $sqldb->end_node = 0; //末端节点_0否1是
                $sqldb->save();
                $v['children'] = $this->get_Tree($db, $v['id'], $level + 1); //递归获取子记录
                if ($v['children'] == null) {
                    $v['children'] = [];
                    $sqldb = mysql::where([['id', '=', $v['id']]])->find();
                    $sqldb->end_node = 1; //末端节点_0否1是
                    $sqldb->save();
                    // unset($v['children']); //如果子元素为空则unset()进行删除，说明已经到该分支的最后一个元素了（可选）
                }
                $tree[] = $v; //将记录存入新数组
            }
        }
        return $tree; //返回新数组
    }




    /** 新增 */
    public function new()
    {
        $query = request()->param(); //请求参数
        // $time_int = time();
        // $time = date('Y-m-d H:i:s', $time_int);
        $sqldb = mysql::create(
            [
                'pid' => isset($query['pid']) ? $query['pid'] : 0, //父ID
                'name' => isset($query['name']) ? $query['name'] : "未命名分类", //名称
                'i' => isset($query['i']) ? $query['i'] : 0, //排序
            ],
            // 许可写入的字段
            [
                'pid', //父ID
                'name', //名称
                'i', //排序
            ]
        );
        // unset($sqldb['sn_pw']); //删除数组中的元素
        $apidb = [
            // 'api' => ["code" => "001", "name" => "用户列表", "help" => $help], //API信息
            'code' => 200, //状态码
            'msg' => '新增成功', //状态信息
            'query' => $query, //请求参数
            // '_header' => request()->header('token'),
            // '_cache' => cache('userdb_' . request()->header('token')),
            // 'data_formerly' => $sqldb, // formerly,now/过去,现在
            'data_now' => $sqldb->toArray(),
            'data' => ['id' => $sqldb->id],
        ];
        // unset($sqldb2); //销毁
        return (json($apidb));
    }
    // 
    /** 修改 */
    public function up()
    {
        // $time_int = time();
        // $time = date('Y-m-d H:i:s', $time_int);
        $query = request()->param(); //请求参数
        $sqldb = mysql::where([
            ['id', '=', $query['id']]
        ])
            ->find();
        // unset($sqldb['sn_pw']); //删除数组中的元素
        $data_formerly = $sqldb->toArray();
        if ($sqldb) {
            $sqldb->name = isset($query['name']) ? $query['name'] : "未命名分类"; //名称
            $sqldb->pid = isset($query['pid']) ? $query['pid'] : 0; //父ID
            $sqldb->i = isset($query['i']) ? $query['i'] : 0; //排序
            $umsg = $sqldb->save();
            if ($umsg !== false) {
                $msg = '更新成功!';
                $code = 200;
            } else {
                $msg = '更新失败!';
                $code = 201;
            }
        } else {
            $msg = '查询与更新失败!';
            $code = 202;
        }
        // unset($sqldb['sn_pw']); //删除数组中的元素
        // unset($sqldb['token']); //删除数组中的元素
        // unset($data_formerly['token']); //删除数组中的元素
        $apidb = [
            'code' => $code, //状态码
            'msg' => $msg, //状态信息
            'query' => $query, //请求参数
            'db_old' => $data_formerly,
            'db_now' => $sqldb->toArray(),
        ];
        // unset($sqldb2); //销毁
        return (json($apidb));
    }
    // 
    /** 删除 */
    public function del()
    {
    }
    //
    /** 列表并生成JSON版本数据 */
    public function List()
    {
        $query = request()->param(); //请求参数
        if (isset($query["spread"])) {
            if ($query["spread"] == "off") {
                $spread = false;
            } else {
                $spread = true;
            }
        } else {
            $spread = false;
        }
        $sqldb = mysql::where([
            ['id', '>', -1]
        ])
            ->order("i", "desc")
            ->select()->toArray(); //以数组方式返回
        for ($i = 0; $i < count($sqldb); $i++) {
            // $sqldb[$i]['title'] = $sqldb[$i]['id'] . ' - ' . $sqldb[$i]['name'];
            $sqldb[$i]['spread'] = $spread; // 查询的树是否展开 off 为收缩，其它 为展开
        }
        // 输出新数组
        // $cateTree = _getSon0($sqldb, 0);//D:\wwwroot\127.0.0.1\tp6\app\admin_v1\common.php
        $cateTree = $this->get_Tree($sqldb, 0);
        $apidb = [
            'msg' => '分类',
            'code' => 200, //状态码
            'cateTree' => $cateTree,
            'query' => $query
        ];

        if ($spread) {
            # 展开树格式...
            Db::name('admin__i_goods_cls_json')
                ->where('name', 'goods_cls_spread_on')
                ->update([
                    'txt_json' => json_encode($cateTree, JSON_UNESCAPED_UNICODE), // 不编码中文
                    'txt_json_unicode' => json_encode($cateTree) // 编码中文
                ]);
        } else {
            Db::name('admin__i_goods_cls_json')
                ->where('name', 'goods_cls_spread_off')
                ->update([
                    'txt_json' => json_encode($cateTree, JSON_UNESCAPED_UNICODE), // 不编码中文
                    'txt_json_unicode' => json_encode($cateTree) // 编码中文
                ]);
        }

        return json($apidb);
    }

    //列表-JSON静态数据
    public function ListJSON()
    {
        $query = request()->param(); //请求参数
        if (isset($query['spread'])) {
            if ($query["spread"] == "off") {
                $cateTree = Db::name('admin__i_goods_cls_json')
                    ->where('name', 'goods_cls_spread_off')
                    ->find();
            } else {
                # 展开树格式...
                $cateTree = Db::name('admin__i_goods_cls_json')
                    ->where('name', 'goods_cls_spread_on')
                    ->find();
            }
            $txt_json = json_decode($cateTree['txt_json']);
            $txt_json_unicode = json_decode($cateTree['txt_json_unicode']);
            if ($txt_json == null || $txt_json == null) {
                $Tree = [
                    'code' => 201, //状态码
                    "msg" => '数据JSON处理错误',
                ];
            } else {
                $Tree = [
                    'code' => 200, //状态码
                    "msg" => $cateTree['msg'],
                    "name" => $cateTree['name'],
                    "txt_json" => $txt_json,
                    "txt_json_unicode" => $txt_json_unicode,
                ];
            }
        } else {
            $Tree = [
                'code' => 202, //状态码
                "msg" => '请求参数错误',
            ];
        }
        $apidb = [
            'msg' => '静态JSON分类树-此接口响应性能更好',
            'code' => 200, //状态码
            'cateTree' => $Tree,
            'query' => $query
        ];
        return json($apidb);
    }
}
